# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from wenlincms.conf import settings
from wenlincms.utils.email import send_approved_mail, send_verification_mail
from wenlincms.utils.models import get_user_model

from wlapps.accounts import get_profile_model, ProfileNotConfigured

User = get_user_model()


class WLUserAdmin(UserAdmin):
    fieldsets = (
        (None, {'fields': ('username', 'password', 'email', 'last_login', 'date_joined',)}),
        ('权限管理', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}),
    )
    list_display = ('id', 'username', 'email', 'is_staff', "is_active", "date_joined", "last_login")
    list_display_links = ('username',)
    ordering = []
    readonly_fields = ['last_login', 'date_joined', ]

    def save_model(self, request, obj, form, change):
        """
        If the ``ACCOUNTS_APPROVAL_REQUIRED`` setting is ``True``,
        send a notification email to the user being saved if their
        ``active`` status has changed to ``True``.
        If the ``ACCOUNTS_VERIFICATION_REQUIRED`` setting is ``True``,
        send a verification email instead.
        """
        must_send_verification_mail_after_save = False
        if change and settings.ACCOUNTS_APPROVAL_REQUIRED:
            if obj.is_active and not User.objects.get(id=obj.id).is_active:
                if settings.ACCOUNTS_VERIFICATION_REQUIRED:
                    # Accounts verification requires an inactive account
                    obj.is_active = False
                    # The token generated by send_verification_mail()
                    # must match the _saved_ User object,
                    # so postpone send_verification_mail() until later
                    must_send_verification_mail_after_save = True
                else:
                    send_approved_mail(request, obj)
        super(WLUserAdmin, self).save_model(request, obj, form, change)
        if must_send_verification_mail_after_save:
            user = User.objects.get(id=obj.id)
            send_verification_mail(request, user, "signup_verify")


try:
    class ProfileInline(admin.StackedInline):
        model = get_profile_model()
        can_delete = False
        template = "admin/profile_inline.html"
        extra = 0


    WLUserAdmin.inlines = (ProfileInline,)
except ProfileNotConfigured:
    pass

if User in admin.site._registry:
    admin.site.unregister(User)
admin.site.register(User, WLUserAdmin)
